package com.weigee.ktv.view.fragment

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.linde.library.activities.MyFragmentActivity
import com.linde.library.util.ToastUtil
import com.weigee.ktv.R
import com.weigee.ktv.presenter.MainPresenter
import com.weigee.ktv.view.interfaces.MainView
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Created by linde on 2017/6/13.
 * LinDe
 */
class MainFragment : BaseFragment(), MainView {
    private val content = MainContentFragment()
    private val leftMenu = MainLeftMenuFragment()
    var presenter: MainPresenter? = null
    var lastPressBackMillis: Long = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        presenter = MainPresenter()
        presenter?.onCreate(savedInstanceState)
        content.mainView = this
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(R.layout.activity_main, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (activity as MyFragmentActivity).onBackPressedListener = object : MyFragmentActivity.OnBackPressedListener {
            override fun onBackPressed(): Boolean {
                if (drawer_layout.isDrawerOpen(Gravity.START)) {
                    drawer_layout.closeDrawer(Gravity.START)
                } else {
                    val now = System.currentTimeMillis()
                    if (now - lastPressBackMillis >= 2500) {
                        ToastUtil.show(drawer_layout, "再按一次返回键退出")
                        lastPressBackMillis = now
                    } else {

                        activity.finish()
                        System.exit(0)
                    }
                }
                return true
            }
        }
        childFragmentManager.beginTransaction()
                .add(R.id.content_frame, content)
                .add(R.id.left_drawer, leftMenu)
                .commit()
    }

    override fun onResume() {
        super.onResume()
        presenter?.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter?.onDestroy()
    }

    override fun taskPreview() {
    }

    override fun taskCompletely() {
    }

    override fun onChangeLeftDrawerState() {
        if (drawer_layout.isDrawerOpen(Gravity.START)) {
            drawer_layout.closeDrawer(Gravity.START)
        } else {
            drawer_layout.openDrawer(Gravity.START)
        }
    }
}